package org.ithasu.tools;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class TimeTools {

	protected TimeTools() {
	}

	// -- Time ----------------------------------------

	public static long getTime() {
		return System.currentTimeMillis();
	}

	public static long getLocalTime() {
		return Calendar.getInstance().getTime().getTime();
	}

	public static TimeZone getLocalTimeZone() {
		return TimeZone.getDefault();
	}

	// -- Infos ----------------------------------------

	public static int getDayOfWeek(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date(time));
		return cal.get(Calendar.DAY_OF_WEEK);
	}

	public static long getMinutesFromMidnight(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date(time));
		return cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
	}

	/** Will always return a positive value */
	public static long getMinutesBetween(int fromDay,
			long fromMinutesFromMidnight, int toDay, long toMinutesFromMidnight) {
		long res = getDaysBetween(fromDay, toDay) * 24 * 60
				+ toMinutesFromMidnight - fromMinutesFromMidnight;
		if (res < 0) {
			res += 7 * 24 * 60;
		}
		return res;
	}

	public static int getDaysBetween(int day1, int day2) {
		if (day2 < day1) {
			day2 += 7;
		}
		return day2 - day1;
	}

	// -- String ----------------------------------------

	private final static SimpleDateFormat defaultFormat = new SimpleDateFormat();
	private final static SimpleDateFormat detailsFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");

	public static String format(long time) {
		return defaultFormat.format(new Date(time));
	}

	public static String formatDetails(long time) {
		return detailsFormat.format(new Date(time));
	}

	public static String minutes(long minutes) {
		long hours = minutes / 60;
		minutes = minutes % 60;

		String res = String.valueOf(minutes);
		res = String.valueOf(hours) + (res.length() < 2 ? ":0" : ":") + res;

		return res;
	}

	/** Initials for day */
	public static String day(int day) {
		switch (day) {
		case Calendar.MONDAY:
			return "Lun";
		case Calendar.TUESDAY:
			return "Mar";
		case Calendar.WEDNESDAY:
			return "Mer";
		case Calendar.THURSDAY:
			return "Jeu";
		case Calendar.FRIDAY:
			return "Ven";
		case Calendar.SATURDAY:
			return "Sam";
		case Calendar.SUNDAY:
			return "Dim";
		default:
			return "?";
		}
	}

	// -- Tests ----------------------------------------

	public static void main(String[] args) {
		int i = 20;
		while (i-- > 0) {
			Console.message(formatDetails(getLocalTime()));
			Console.message(minutes(getMinutesFromMidnight(getLocalTime())));
			Console.message("Day of week: " + getDayOfWeek(getLocalTime()));
			Console.sleep(100);
		}
	}

}
